﻿Imports ACompany.OrderProcessing.Infrastructure
Imports System.Text

Public Class Address

    Private _street As String
    Private _city As String
    Private _county As String
    Private _postCode As String

    Public Sub New()
        ' Default Constructor required for NHibernate
    End Sub

    Public Sub New(ByVal Street As String, ByVal City As String, ByVal County As String, ByVal PostCode As String)
        _street = Street
        _city = City
        _county = County
        _postCode = PostCode

        validate()
    End Sub

    Public ReadOnly Property Street() As String
        Get
            Return _street
        End Get
    End Property

    Public ReadOnly Property City() As String
        Get
            Return _city
        End Get
    End Property

    Public ReadOnly Property County() As String
        Get
            Return _county
        End Get
    End Property

    Public ReadOnly Property PostCode() As String
        Get
            Return _postCode
        End Get
    End Property

    Protected Overridable Sub validate()

        Dim sbBrokenRules As New StringBuilder

        If String.IsNullOrEmpty(Me.Street.Trim) Then
            sbBrokenRules.AppendLine("Street is a required value")
        Else
            If Me.Street.Length > 50 Then
                sbBrokenRules.AppendLine( _
                  "Street should be 50 chars or less")
            End If
        End If

        If String.IsNullOrEmpty(Me.City.Trim) Then
            sbBrokenRules.AppendLine("City is a required value")
        Else
            If Me.City.Length > 50 Then
                sbBrokenRules.AppendLine( _
                    "City should be 50 chars or less")
            End If
        End If

        If String.IsNullOrEmpty(Me.County.Trim) Then
            sbBrokenRules.AppendLine("County is a required value")
        Else
            If Me.County.Length > 50 Then
                sbBrokenRules.AppendLine( _
                     "County should be 50 chars or less")
            End If
        End If

        If String.IsNullOrEmpty(Me.PostCode.Trim) Then
            sbBrokenRules.AppendLine("PostCode is a required value")
        Else
            If Me.PostCode.Length > 50 Then
                sbBrokenRules.AppendLine( _
                      "PostCode should be 50 chars or less")
            End If
        End If

        If Not String.IsNullOrEmpty(sbBrokenRules.ToString) Then
            Throw New InvalidAddressException( _
                 String.Format( _
 "Broken rules on Address, please correct the following errors:{0}{1}", Environment.NewLine, sbBrokenRules.ToString))
        End If

    End Sub
End Class
